package agent

import (
	"fmt"
	"time"

	"github.com/sashabaranov/go-openai"
)

// ReActSession 表示一个ReAct会话
type ReActSession struct {
	ID            string                         `json:"id"`           // 会话ID
	Goal          string                         `json:"goal"`         // 目标描述
	Steps         []ReActStep                    `json:"steps"`        // 步骤历史
	Status        string                         `json:"status"`       // 状态: reasoning, acting, completed, failed
	CreatedAt     string                         `json:"created_at"`   // 创建时间
	CompletedAt   string                         `json:"completed_at"` // 完成时间
	Messages      []openai.ChatCompletionMessage `json:"messages"`     // 消息历史
	systemMessage string                         `json:"-"`            // 系统消息（内部使用）
}

// SessionStatus 定义会话状态常量
type SessionStatus string

const (
	StatusReasoning SessionStatus = "reasoning"
	StatusActing    SessionStatus = "acting"
	StatusCompleted SessionStatus = "completed"
	StatusFailed    SessionStatus = "failed"
)

// NewSession 创建一个新的ReAct会话
func NewSession(goal string) *ReActSession {
	return &ReActSession{
		ID:        fmt.Sprintf("react_%d", time.Now().Unix()),
		Goal:      goal,
		Steps:     []ReActStep{},
		Status:    string(StatusReasoning),
		CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
		Messages:  []openai.ChatCompletionMessage{},
	}
}

// AddStep 添加步骤到会话
func (s *ReActSession) AddStep(step ReActStep) {
	s.Steps = append(s.Steps, step)
}

// GetSteps 获取所有步骤
func (s *ReActSession) GetSteps() []ReActStep {
	return s.Steps
}

// Complete 标记会话为完成
func (s *ReActSession) Complete() {
	s.Status = string(StatusCompleted)
	s.CompletedAt = time.Now().Format("2006-01-02 15:04:05")
}

// Fail 标记会话为失败
func (s *ReActSession) Fail() {
	s.Status = string(StatusFailed)
	s.CompletedAt = time.Now().Format("2006-01-02 15:04:05")
}

// GetStepCount 获取步骤数量
func (s *ReActSession) GetStepCount() int {
	return len(s.Steps)
}

// AddMessage 添加消息到历史
func (s *ReActSession) AddMessage(role string, content string) {
	s.Messages = append(s.Messages, openai.ChatCompletionMessage{
		Role:    role,
		Content: content,
	})
}

// GetMessages 获取消息历史
func (s *ReActSession) GetMessages() []openai.ChatCompletionMessage {
	return s.Messages
}

// SetSystemMessage 设置系统消息
func (s *ReActSession) SetSystemMessage(content string) {
	s.systemMessage = content
}
